import {Modal, Upload} from "antd"
import {useEffect, useState} from "react";
import {PlusOutlined} from "@ant-design/icons";
import {BASE_URL} from "@utils/constants.js";
import {api_file_upload} from "@utils/api.js";

export default (props) => {
    const {value, onChange, max = 1} = props;
    const [fileList, setFileList] = useState([]);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');

    const getBase64 = (file) =>
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
        });

    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url?.substring(file.url?.lastIndexOf('/') + 1));
    };
    useEffect(() => {
        if (!value) return
        if (max > 1) {
            setFileList(value.map((item, index) => {
                let url = BASE_URL + item;
                if (item.startsWith('http')) url = item;
                return {
                    uid: index,
                    name: item?.split('/')?.pop(),
                    status: 'done',
                    url,
                }
            }))
        } else if (max === 1) {
            let url = BASE_URL + value;
            if (value?.startsWith('http')) url = value;
            setFileList([{
                uid: '-1',
                name: value?.split('/')?.pop(),
                status: 'done',
                url
            }]);
        }
    }, []);
    return (
        <>
            <Upload
                action={BASE_URL + api_file_upload}
                headers={{
                    token: localStorage.getItem('token') || '',
                }}
                listType="picture-card"
                fileList={fileList}
                onPreview={handlePreview}
                onChange={(e) => {
                    if (e.file?.response?.code?.value === 200) {
                        let item = e.fileList.find((item) => item.uid === e.file.uid)
                        if (item) item.url = e.file.response.body.path
                    }
                    setFileList(e.fileList)
                    if (max > 1) {
                        onChange(e.fileList.map((item) => item.url))
                    } else {
                        onChange(e.fileList[0]?.url)
                    }
                }}
            >
                {fileList.length >= max ? null : (<div>
                    <PlusOutlined/>
                    <div style={{marginTop: 8}}>上传图片</div>
                </div>)
                }
            </Upload>
            <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={() => setPreviewOpen(false)}>
                <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
        </>
    )
}